package com.gdou.im.server.codeC;

import com.alibaba.fastjson.JSONObject;
import com.gdou.im.protocol.Packet;
import com.gdou.im.protocol.PacketCodeC;
import com.gdou.im.protocol.data.Data;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageCodec;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @ProjectName: demo
 * @Package: com.gdou.im.server.codeC
 * @ClassName: WebSocketProtocolCodec
 * @Author: carrymaniac
 * @Description: WebSocketProtocolCodec
 * @Date: 2020/6/16 4:35 下午
 * @Version:
 */
@Component
public class WebSocketProtocolCodec extends MessageToMessageCodec<TextWebSocketFrame, Packet> {
    @Override
    protected void encode(ChannelHandlerContext ctx, Packet msg, List<Object> out) throws Exception {
        //将Packet编译成TextWebSocketFrame
        out.add(new TextWebSocketFrame(JSONObject.toJSONString(msg)));
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, TextWebSocketFrame msg, List<Object> out) throws Exception {
        String text = msg.text();
        Packet packet = JSONObject.parseObject(text, Packet.class);
        out.add(packet);
    }
}
